/**
 * QUANSHI.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.quanshi.scheduler.core.thread;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.quanshi.scheduler.core.base.RegistryConfig;
import com.quanshi.scheduler.core.base.Ret;
import com.quanshi.scheduler.core.biz.model.RegistryParam;
import com.quanshi.scheduler.core.utils.AdminApiUtils;
import com.quanshi.scheduler.core.utils.IpUtils;

/**
 * 处理器注册类
 * 
 * @author chinaxiang
 * @version 2017年7月7日 下午11:26:34
 */
public class ExecutorRegistryThread extends Thread {

    private static Logger                 logger   = LoggerFactory.getLogger(ExecutorRegistryThread.class);

    private static ExecutorRegistryThread instance = new ExecutorRegistryThread();

    public static ExecutorRegistryThread getInstance() {
        return instance;
    }

    private Thread  registryThread;
    private boolean toStop = false;

    public void start(final int port, final String ip, final String appName) {
        // valid
        if (!(AdminApiUtils.allowCallApi() && (appName != null && appName.trim().length() > 0))) {
            logger.warn(">>>>>>>>>>>> job executor registry config fail.");
            return;
        }

        // executor address (generate address = ip:port)
        final String executorAddress;
        if (ip != null && ip.trim().length() > 0) {
            executorAddress = ip.trim().concat(":").concat(String.valueOf(port));
        } else {
            executorAddress = IpUtils.getIpPort(port);
        }

        registryThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!toStop) {
                    try {
                        RegistryParam registryParam = new RegistryParam(RegistryConfig.RegistType.EXECUTOR.name(), appName, executorAddress);
                        Ret<String> registryResult = AdminApiUtils.callApiFailover(AdminApiUtils.REGISTRY, registryParam);
                        logger.debug(">>>>>>>>>>> job executor registry {}, registryParam:{}, registryResult:{}", (registryResult.getCode() == Ret.SUCCESS_CODE ? "success" : "fail"), registryParam.toString(), registryResult.toString());
                    } catch (Exception e) {
                        logger.error(">>>>>>>>>>> job executorRegistryThread Exception:", e);
                    }

                    try {
                        TimeUnit.SECONDS.sleep(RegistryConfig.BEAT_TIMEOUT);
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        });
        registryThread.setDaemon(true);
        registryThread.start();
    }

    public void toStop() {
        toStop = true;
    }
}
